package com.hoshiicloud.user.service.impl.usercenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.usercenter.MemberAccount;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.usercenter.MemberAccountMapper;
import com.hoshiicloud.user.service.usercenter.IMemberAccountService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户账户Service接口实现类
 *
 * @author : yangcheng
 * @date : 2019/5/10 14:45
 * @mail : maiboyc@163.com
 **/
@Service
public class MemberAccountServiceImpl extends ServiceImpl<MemberAccountMapper, MemberAccount> implements IMemberAccountService {

    // id生成Service
    @Autowired
    private IdGeneratorService idGeneratorService;

    // 用户账户信息Service
    @Autowired
    private IPlatConsumerService platUserService;

    /**
     * 根据id获取
     * @param id ID
     * @return MemberAccount
     */
    @Cacheable(cacheNames = "memberAccount", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "用户管理-用户账户信息管理-根据ID查询用户账户信息")
    @Override
    public MemberAccount getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 根据一组id
     * @param ids id组
     * @return List<MemberAccount>
     */
    @Cacheable(cacheNames = "memberAccount", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#ids")
    @Logable(authName = "用户管理-用户账户信息管理-根据ID组查询用户账户信息")
    @Override
    public List<MemberAccount> getByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAccount", allEntries = true)
    @Logable(authName = "用户管理-用户账户信息管理-新增用户账户信息")
    @Override
    public Long insert(MemberAccount entity) throws ServiceException{
        // 调用主键生成微服务生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (id == null) {
            throw new ServiceException(CommonError.error("新增用户账户失败,生成ID主键失败"));
        }
        // 调用用户基本信息Service检查用户账户信息是否存在
        PlatConsumer platConsumer = platUserService.getById(entity.getUserId());
        if (platConsumer == null) {
            throw new ServiceException(CommonError.error("新增用户账户失败，没有找到对应的用户基本信息"));
        }
        // 自动生成id，创建日期 修改日期 创建人 修改人 删除标识
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedBy("admin");// 需要拿当前的登录人
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        entity.setDeleted(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增用户账户失败"));
        }
        return entity.getId();
    }

    /**
     * 修改
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAccount", allEntries = true)
    @Logable(authName = "用户管理-用户账户信息管理-修改用户账户信息")
    @Override
    public Long update(MemberAccount entity) throws ServiceException{
        // 自动填入修改时间 修改人
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy("admin1");// 需要拿当前的登录人
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改用户账户失败"));
        }
        return entity.getId();
    }

    /**
     * 查询
     * @param entity 查询参数实体
     * @return IPage<MemberAccount>
     */
    @Cacheable(cacheNames = "memberAccount", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.pageIndex+':'+#entity.pageSize+':'+#entity.userId+':'+#entity.settlement")
    @Logable(authName = "用户管理-用户账户信息管理-分页查询用户账户信息")
    @Override
    public IPage<MemberAccount> List(MemberAccount entity) {
        QueryWrapper<MemberAccount> queryWrapper = new QueryWrapper();
        IPage<MemberAccount> page = new Page();
        if(entity.getPageIndex() != null) {
            page.setCurrent(entity.getPageIndex());
        }
        if(entity.getPageSize() != null){
            page.setSize(entity.getPageSize());
        }
        // 用户ID
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        // 结算方式
        if (entity.getSettlement() != null) {
            queryWrapper.eq("settlement", entity.getSettlement());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 删除
     * @param id ID
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAccount", allEntries = true)
    @Logable(authName = "用户管理-用户账户信息管理-删除用户账户信息")
    @Override
    public boolean delete(Long id) throws ServiceException{
        MemberAccount memberAccount = this.getById(id);
        memberAccount.setDeleted(1);
        int row = baseMapper.updateById(memberAccount);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除用户账户信息失败"));
        } else {
            return true;
        }
    }

    /**
     * 根据消费者id查找消费者账户
     * @param entity 查询参数
     * @return IPage<MemberAccount>
     */
    @Cacheable(cacheNames = "memberAccount", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.userId+':'+#entity.settlement")
    @Logable(authName = "用户管理-用户账户信息管理-根据查询参数查询用户账户信息")
    @Override
    public List<MemberAccount> getMemberAccounts(MemberAccount entity) {
        QueryWrapper<MemberAccount> queryWrapper = new QueryWrapper();
        // 用户ID
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        // 结算方式
        if (entity.getSettlement() != null) {
            queryWrapper.eq("settlement", entity.getSettlement());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据消费者ID获取消费者账户
     * @param consumerId 消费者ID
     * @return MemberAccount
     */
    @Cacheable(cacheNames = "memberAccount", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#consumerId")
    @Logable(authName = "用户管理-用户账户信息管理-根据消费者ID查询用户账户信息")
    @Override
    public MemberAccount getMemberAccountByConsumerId(Long consumerId) {
        QueryWrapper<MemberAccount> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", consumerId);
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        List<MemberAccount> memberAccounts = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(memberAccounts)) {
            return memberAccounts.get(0);
        } else {
            return null;
        }
    }

}